#!/usr/bin/python3
# -*- coding: utf-8 -*-

import logging, ast
from aiohttp import web
from aioweb import corelib
# import aiohttp_jinja2

from . import db


routes = web.RouteTableDef()
module_name = 'clipboard'


@routes.get('/%s' % module_name)
# @aiohttp_jinja2.template('clipboard.html')
@corelib.template('clipboard.html')
async def records_index(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '/root')
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    return data


@routes.get('/%s/items' % module_name)
async def clipboard_items(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        index = int(params.get('index', '1'))
        pagesize = int(params.get('pagesize', '36'))
        items = await corelib.load_items('Clipboard', order_by={'id': False})
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})

@routes.get('/%s/items/{index}' % module_name)
async def clipboard_items_index(request):
    pagesize = 12
    data = {'items': [], 'page': {'total': 0, 'pages': 0, 'index': 1, 'size': pagesize}}
    try:
        params = await corelib.parse_param(request)
        # index = int(params.get('index', '1'))
        index = int(request.match_info.get('index', '1'))
        pagesize = int(params.get('pagesize', '36'))
        search_key = params.get('q', None)
        items = await corelib.load_page('Clipboard', index, pagesize=pagesize, like={'content': search_key}, order_by={'id': False})
        # items = await corelib.load_items('Clipboard', order_by={'id': False})
        
        # clip_ids = [item['id'] for item in items["items"] if "'kind': 'file'" in item["content"]]
        # clip_datas = await corelib.load_items('ClipData', in_={'clip_id': clip_ids})
        # clip_datas = {item['clip_id']: item["text"] for item in clip_datas['items']}
        # for item in items["items"]: 
        #     if "'kind': 'file'" not in item["content"] or item["id"] not in clip_datas.keys():
        #         item['type'] = 'text'
        #         continue
        #     print(item)
        #     item['type'] = (ast.literal_eval(item["content"]))["type"]
        #     if  item['type'].startswith('image'):
        #         item["content"] = clip_datas.get(item["id"], "")
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    return web.json_response({'code': 0, 'msg': data})


@routes.get('/%s/datas' % module_name)
async def clipboard_datas(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        clip_ids = params.get('ids', '-1')

        items = await corelib.load_items('Clipboard', in_={'id': clip_ids}, order_by={'id': False})
        clip_ids = [item['id'] for item in items["items"] if "'kind': 'file'" in item["content"]]
        clip_datas = await corelib.load_items('ClipData', in_={'clip_id': clip_ids})
        clip_datas = {item['clip_id']: item["text"] for item in clip_datas['items']}
        for item in items["items"]: 
            if "'kind': 'file'" not in item["content"] or item["id"] not in clip_datas.keys():
                item['type'] = 'text'
                continue
            item['type'] = (ast.literal_eval(item["content"]))["type"]
            if  item['type'].startswith('image'):
                item["content"] = clip_datas.get(item["id"], "")
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})

@routes.get('/%s/data' % module_name)
async def clipboard_data(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        id = params.get('id', '-1')
        kind = params.get('kind', '')  # string/file
        items = await corelib.load_items('ClipData', filter={'clip_id': id, 'kind': kind})
        items = [{'content': item['text'], 'type': item["type"]} for item in items["items"]]
        data = dict(data, **{'items': items})
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/clipboard')
async def save_clipboard(request):
    try:
        params = await corelib.parse_param(request)
        text = params.get('text', '')
        data = params.get('data', [])

        if (not text or not text.strip()) and len(data) <= 0:
            if (not text or not text.strip()):
                return {'code': -1, 'field': 'text', 'msg': 'text is null'}
            return {'code': -1, 'field': 'text', 'msg': 'params is null'}
        for item in data:
            if item['kind'] == 'file' and text == '':
                text = str({'name': item['name'], 'kind': item['kind'],
                            'type': item['type'], 'size': item['size']})
        user_id = 0
        user = request.__user__ if hasattr(request, '__user__') else None
        if user:
            user_id = user['id']
        ids = corelib.save(
            'Clipboard', [{'content': text, 'user_id': user_id}])
        for item in data:
            item['clip_id'] = ids[0].id
        corelib.save('ClipData', data)
        data = {'code': 0, 'msg': f'保存成功: {ids[0].id}'}
        return data
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return {'code': -1, 'msg': str(e)}


@routes.get('/clipboard/delete/{id}')
async def delete_clipboard(request):
    try:
        id = request.match_info['id']
        items = await corelib.load_items('Clipboard', in_={'id': [id]})
        if not items['items'] or len(items['items']) <= 0:
            return {'code': -1, 'msg': f'[{id}]不存在'}
        items = await corelib.load_items('ClipData', in_={'clip_id': [id]})
        ids = [item['id'] for item in items['items']]
        corelib.delete('ClipData', ids)
        corelib.delete('Clipboard', [id])
        return {'code': 0, 'msg': f'删除[{id}]成功'}
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return {'code': -1, 'msg': str(e)}

@routes.get('/%s/export/{id}' % module_name)
async def clipboard_export(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        id = int(request.match_info.get('id', '1'))
        items = await corelib.load_items('Clipboard', filter={'id': id}, order_by={'id': False})
        for item in items['items']:
            data = await corelib.load_items('ClipData', filter={'clip_id': item['id']})
            del item["id"]
            del item["user_id"]
            del item["created_at"]
            del item["created_date"]
            del item["created_stamp"]
            del item["updated_at"]
            del item["updated_date"]
            del item["updated_stamp"]
            for data_item in data['items']:
                del data_item["id"]
                del data_item["clip_id"]
                del data_item["created_at"]
                del data_item["created_date"]
                del data_item["created_stamp"]
                del data_item["updated_at"]
                del data_item["updated_date"]
                del data_item["updated_stamp"]
            item['data'] = data["items"]
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})

@routes.get('/%s/export' % module_name)
async def clipboard_export(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        items = await corelib.load_items('Clipboard', order_by={'id': False})
        for item in items['items']:
            data = await corelib.load_items('ClipData', filter={'clip_id': item['id']})
            del item["id"]
            del item["user_id"]
            del item["created_at"]
            del item["created_date"]
            del item["created_stamp"]
            del item["updated_at"]
            del item["updated_date"]
            del item["updated_stamp"]
            for data_item in data['items']:
                del data_item["id"]
                del data_item["clip_id"]
                del data_item["created_at"]
                del data_item["created_date"]
                del data_item["created_stamp"]
                del data_item["updated_at"]
                del data_item["updated_date"]
                del data_item["updated_stamp"]
            item['data'] = data["items"]
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})

@routes.post('/clipboard/import')
async def import_clipboard(request):
    try:
        params = await corelib.parse_param(request)
        items = params.get('items', [])
        if len(items) <= 0:
            return {'code': -1, 'field': 'items', 'msg': 'items is empty'}
        user = request.__user__ if hasattr(request, '__user__') else None
        user_id = 0
        if user:
            user_id = user['id']
        items_data = {}
        items_ = []
        for item in items:
            content = item.get('content', '')
            if len(content) <= 0:
                continue
            items_data[content] = item['data']
            items_.append({'content': content, 'user_id': user_id})
        items_ = corelib.save('Clipboard', items_)
        data_list = []
        for item in items_:
            if item.content not in items_data: continue
            for data in items_data[item.content]:
                data["clip_id"] = item.id
                data_list.append(data)
        corelib.save('ClipData', data_list)
        data = {'code': 0, 'msg': '导入成功'}
        return data
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return {'code': -1, 'msg': str(e)}
